<template>
  <div>
    <!--    面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><b>题目管理</b></el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/AddSet' }">创建题目集</el-breadcrumb-item>
      <el-breadcrumb-item><span style="color: #545c99">我的题目集</span></el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <h1>查询我的题目集</h1>
      <!--      搜索与添加区域-->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input placeholder="请输入内容" v-model="queryInfo.searchInfo" clearable @clear="getMySetlist">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
      </el-row>
      <el-divider content-position="right"><i class="el-icon-edit"></i></el-divider>
      <el-table
        v-loading="loading4"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        :data="pagetestlist" :stripe="true">
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column align="center" label="+" width="40" fixed="left">
          <template slot-scope="scope">
            <!--              添加班级到题目集按钮-->
            <el-popover
              placement="bottom"
              title="添加班级"
              width="100"
              trigger="hover"
              content="添加班级到题目集">
                 <el-button slot="reference" style="color: #545c99" type="text" icon="el-icon-plus" size="mini" :enterable="false" @click="addClassToSet(scope.row.setId)"></el-button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="setName" label="题目集名称" width="130px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="查看详情">
              <el-button type="text" @click="JumpToClass(scope.row)">{{scope.row.setName}}</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="teachName" label="创建者" width="100px">
          <template slot-scope="scope">
            <el-popover trigger="hover">
              <el-tag>创建者工号</el-tag>
              <el-tag type="success"> {{scope.row.teachId}}</el-tag>
              <div slot="reference">
                {{scope.row.teachName}}
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column sortable align="center" prop="startTime" label="开始时间">
          <template slot-scope="scope">
            <span style="color: #545c99">
              {{scope.row.startTime.substring(0,16)}}
            </span>
          </template>
        </el-table-column>
        <el-table-column sortable align="center" prop="overTime" label="截止时间">
          <template slot-scope="scope">
            <span v-if="Date.parse(scope.row.overTime) > new Date()" style="color: #795da3">
              {{scope.row.overTime.substring(0,16)}}
            </span>
            <span v-else style="color: #df5000">
              {{scope.row.overTime.substring(0,16)}}
            </span>
          </template>
        </el-table-column>
        <!--        操作-->
        <el-table-column align="center" label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <!--              修改题目集按钮-->
            <el-tooltip effect="dark" content="修改题目集" placement="top">
              <el-button style="background-color: #545c64;color: white" icon="el-icon-edit" size="mini" :enterable="false" @click="editSetDialog(scope.row)"></el-button>
            </el-tooltip>
            <!--              删除题目集按钮-->
            <el-tooltip effect="dark" content="删除题目集" placement="bottom">
              <el-button type="danger" icon="el-icon-delete" size="mini" :enterable="false" @click="removeSetById(scope.row.setId,scope.row.teachId)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        hide-on-single-page
        :page-sizes="[10, 15, 20, 30]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--      修改题目的对话框-->
    <el-dialog
      title="修改题目"
      :visible.sync="SetDialogVisible"
      width="58%" @close="SetDialogClosed">
      <!--      内容主体区域-->
      <el-form label-width="100px" status-icon :model="EditSetForm" ref="AddTestFormRef">
        <el-form-item label="题目集名字" prop="name" required>
          <el-input v-model="EditSetForm.setName" autocomplete="off" placeholder="请输入题目集名字"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间"  prop="startTime" required>
              <el-date-picker
                size="large"
                v-model="EditSetForm.startTime"
                type="datetime"
                placeholder="选择开始时间"
                default-time="12:00:00"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" label-width="120px" prop="overTime" required>
              <el-date-picker
                v-model="EditSetForm.overTime"
                type="datetime"
                placeholder="选择结束时间"
                default-time="23:00:00"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!--      底部区域-->
      <span slot="footer" class="dialog-footer">
           <el-row>
          <el-col :span="4" :offset="5" >
            <el-button class="white_btn" @click="resetTest">重 置</el-button>
          </el-col>
          <el-col :span="4" :offset="5">
            <el-button class="new_btn" @click="editSet">修 改</el-button>
          </el-col>
        </el-row>
        </span>
    </el-dialog>

<!--    添加班级到题目集里-->
    <el-dialog
      title="添加班级到题目集"
      :visible.sync="addClassToVisible"
      width="58%" @close="addClassToClosed">
      <!--      内容主体区域-->
      <el-form  status-icon :model="addClassForm" ref="addClassFormRef">
        <el-form-item label="选择班级" label-width="42%" prop="classId" required>
          <el-autocomplete
            v-model="name"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入要添加的班级"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
      </el-form>
      <!--      底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="4" :offset="5" >
            <el-button class="white_btn" @click="resetAdd">重 置</el-button>
          </el-col>
          <el-col :span="4" :offset="5">
            <el-button class="new_btn" @click="addClass">添 加</el-button>
          </el-col>
        </el-row>
        </span>
    </el-dialog>

<!--    展示该题目集下的班级列表-->
    <el-dialog style="z-index: 10" :title="'题目集'+ setId + 'の班级信息'"
               :visible.sync="showClass" width="50%"
               @close="JumpClosed" class="role-mask">
      <!--        表格-->
      <el-row style="font-size: 1.1em;margin-top: 10px">
        <el-col :span="12">
          <b>题目集名称：</b>{{this.setName}}
        </el-col>
        <el-col :span="6" :offset="6" v-if="ClassList[0]">
          <el-button @click="DetailInfo" type="text" style="color: #545c99">
            <b>点击查看详情</b>
          </el-button>
        </el-col>
      </el-row>
      <el-table
        height="280"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading" :data="ClassList">
        <el-table-column fixed type="index" label="#"></el-table-column>
        <el-table-column align="center" prop="name" label="班级名称">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="查看详情">
              <el-button type="text" @click="JumpToDetails(scope.row)">{{scope.row.name}}</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="count" sortable label="人数">
          <template slot-scope="scope">
            <span v-if="scope.row.count" style="color: #545c99">{{scope.row.count}}</span>
            <span v-else style="color: #df5000">{{scope.row.count}}</span>
            人
          </template>
        </el-table-column>
<!--        删除-->
        <el-table-column align="center" label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <!--              删除班级按钮-->
            <el-tooltip effect="dark" content="删除班级" placement="bottom">
              <el-button type="danger" icon="el-icon-delete" size="mini" :enterable="false" @click="removeClassById(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--      底部区域-->
      <span slot="footer" class="dialog-footer">
            <el-row :gutter="20">
                <el-col :span="3" :offset="10">
                      <el-button class="new_btn" @click="JumpClosed">关 闭</el-button>
                </el-col>
            </el-row>
        </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'FindSet',
  data () {
    return {
      queryInfo: {
        // 模糊搜索
        searchInfo: '',
        // 当前页数
        pagenum: 1,
        pagesize: 10
      },
      total: 0,
      loading4: true, // 加载我的题目集列表
      // 我的所有题目集
      MySetlist: [],
      SetDialogVisible: false,
      EditSetForm: {
        setId: '',
        setName: '',
        teachId: '',
        teachName: '',
        startTime: '',
        overTime: ''
      },
      addClassToVisible: false, //添加班级到题目集窗口
      addClassForm:{
        classId:'',
        setId:''
      },
      // 远程拉取数据
      ClassName: [],
      timeout:  null,
      name: '',
      // 获取该题目集下班级列表
      ClassList: [],
      showClass: false, // 展示班级
      loading: true, // 加载班级列表
      setName: '',
      setId: ''
    }
  },
  created () {
    this.getMySetlist()
  },
  methods: {
    async getMySetlist () {
      const { data: res } = await this.$http.get('/set/findByTeach/' + localStorage.getItem('username'))
      console.log(res.data)
      if (res.status !== 200) {
        return this.$message.error('获取题目集失败!')
      }
      this.MySetlist = res.data
      if (this.MySetlist.length === res.data.length){
        this.total = res.data.length
        this.loading4 = false
      }
    },
    // 监听 pagesize 改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getMySetlist()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getMySetlist()
    },
    // 修改题目
    editSetDialog(list) {
      this.SetDialogVisible = true
      console.log(list)
      this.EditSetForm = list
    },
    // 删除题目集
    async removeSetById (id,teacher) {
      const confirmResult = await this.$confirm('此操作将永久删除该题目集 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('/set/delete/',{data:{setId:id,teachId:teacher}} )
      if (res.status !== 200) {
        return this.$message.error(res.msg)
      }
      this.$message.success('删除题目集成功!')
      this.getMySetlist()
    },
    resetTest () {
      this.$refs.EditSetFormRef.resetFields()
    },
    // 监听修改题目对话框的关闭事件
    SetDialogClosed () {
      this.$refs.EditSetFormRef.resetFields()
    },
    async editSet (){
      const { data: res } = await this.$http.put('/set/update/',this.EditSetForm )
      if (res.status !== 200) {
        return this.$message.error(res.msg)
      }
      this.$message.success('修改题目集成功!')
      this.SetDialogVisible = false
      this.getMySetlist()
    },
    addClassToSet(id){
      this.addClassToVisible = true
      this.addClassForm.setId = id
      console.log(id)
    },
    resetAdd () {
      this.$refs.addClassFormRef.resetFields()
      this.name = ''
    },
    addClassToClosed(){
      this.name = ''
      this.$refs.addClassFormRef.resetFields()
    },
    // 加载所有班级
    async loadAll() {
      const { data: res } = await this.$http.get('/class/allOfTeacher/' + localStorage.getItem('username'))
      console.log(res.data)
      if (res.status !== 200) {
        return this.$message.error(res.msg)
      }
      var arr = []
      res.data.forEach(function (item) {
        arr.push({'classId': item.id , 'value': item.name})
      })
      this.ClassName  = arr
      console.log(arr)
      return arr
    },
    // 远程获取数据
    querySearchAsync(queryString, cb) {
      var ClassName = this.ClassName;
      var results = queryString ? ClassName.filter(this.createStateFilter(queryString)) : ClassName;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (String(state.value).toLowerCase().indexOf(queryString.toLowerCase()) > -1);
      };
    },
    handleSelect(item) {
      this.addClassForm.classId = item.classId
      console.log(this.addClassForm.classId);
    },
    async addClass (){
      console.log(this.addClassForm)
      const { data: res } = await this.$http.post('/class/addToSet/',this.addClassForm )
      if (res.status !== 200) {
        return this.$message.error(res.msg)
      }
      this.$message.success('添加成功!')
      this.addClassToVisible = false
    },
    JumpClosed () {
      this.showClass = false
    },
    // 删除班级
    async removeClassById (id) {
      const confirmResult = await this.$confirm('此操作将从该题目集中删除此班级, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 若用户确认删除，则返回值为字符串 confirm
      // 若取消删除，返回 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('/class/deleteFromSet/',{data:{classId: id, setId: this.setId}})
      if (res.status !== 200) {
        return this.$message.error(res.msg)
      }
      this.$message.success('删除成功!')
      this.getClassList()
    },
   JumpToClass (list){
      this.showClass = true
      this.setName = list.setName
      this.setId = list.setId
      console.log(list)
      this.getClassList()
    },
    JumpToDetails(list){
      var classId = list.id
      var name = list.name
      // 跳转
      window.sessionStorage.setItem('activePath', 'ClassInfo')
      this.$router.push({path: '/StuDetails', query: {classId: classId, name: name}})
      this.$router.go(0)
    },
    async getClassList(){
      const { data: res } = await this.$http.get('/class/allOfSet/' + this.setId)
      if (res.status !== 200) {
        return this.$message.error(res.msg)
      }
      this.ClassList = res.data
      if (this.ClassList.length === res.data.length){
        this.loading = false
      }
    },
    DetailInfo(){
      this.$router.push({path: '/SetDetails', query: {setId: this.setId, setName: this.setName}})
    },
  },
  computed: {
    pagetestlist: function () {
      var search = this.queryInfo.searchInfo
      if (search) {
        return this.MySetlist.filter(function (data) {
          return Object.keys(data).some(function (key) {
            return String(data[key]).toLowerCase().indexOf(search) > -1
          })
        })
      }
      return this.MySetlist.slice((this.queryInfo.pagenum - 1) * this.queryInfo.pagesize, this.queryInfo.pagenum * this.queryInfo.pagesize)
    }
  },
  mounted() {
    this.ClassName = this.loadAll();
  }
}
</script>

<style scoped>

</style>
